package com.example.demo;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * okhttp连接池单例
 *
 * @author duanzm
 * @create 2018-10-11 16:15
 **/
public class OkHttpUtil {
    private OkHttpUtil() {
    }

    public static OkHttpClient getInstance() {
        return Singleton.INSTANCE.getInstance();
    }

    private static enum Singleton {
        INSTANCE;
        private OkHttpClient singleton;

        private Singleton() {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.connectTimeout(60L, TimeUnit.SECONDS);
            builder.readTimeout(60L, TimeUnit.SECONDS);
            builder.writeTimeout(60L, TimeUnit.SECONDS);
            ConnectionPool connectionPool = new ConnectionPool(50, 60, TimeUnit.SECONDS);
            builder.connectionPool(connectionPool);
            singleton = builder.build();
        }

        public OkHttpClient getInstance() {
            return singleton;
        }
    }

    /**
     * 写入网页文字
     */
    public static String get(String url, Map<String, String> params,FileOutputStream fos,int j) {
        long star=System.currentTimeMillis();
        try {
            FormBody.Builder builder = new FormBody.Builder();
            for (Map.Entry<String, String> m : params.entrySet()) {
                builder.add(m.getKey(), m.getValue());
            }
            Request request = new Request.Builder().get().url(url).build();
            Response response = OkHttpUtil.getInstance().newCall(request).execute();
            if (response.isSuccessful()) {
                System.out.println(System.currentTimeMillis()-star);
                String content = response.body().string();
                Document doc = Jsoup.parse(content);
                Elements bookname = doc.getElementsByClass("bookname");
                Element element1 = bookname.get(0);
                Element child = element1.child(0);
                String text1 = child.text();
                Element text = doc.getElementById("content");
                star=System.currentTimeMillis();
                String wenben = fiter(text.getAllElements().text());
                System.out.println(System.currentTimeMillis()-star);
                star=System.currentTimeMillis();
                try {
                    fos.write(" \r\n".getBytes());
                    fos.write(" \r\n".getBytes());
                    fos.write(" \r\n".getBytes());
                    fos.write(text1.getBytes(StandardCharsets.UTF_8));
                    fos.write(" \r\n".getBytes());
                    fos.write(" \r\n".getBytes());
                    fos.write(" \r\n".getBytes());
                    fos.write(wenben.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println(System.currentTimeMillis()-star);
                Elements div = doc.getElementsByClass("bottem2");
                Element element = div.get(0);
                Elements A = element.getAllElements();
                Element element2 = A.get(4);
                String oA=element2.attr("href");
                if(oA.indexOf("index.html")!=-1){
                    return null;
                }
                return "https://www.biqugetv.com" + oA;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String URL="";
    /**
     * 写入网页文字1
     */
    public static String get1(String url, Map<String, String> params,FileOutputStream fos,int j) {
        long star=System.currentTimeMillis();
        try {
            FormBody.Builder builder = new FormBody.Builder();
            for (Map.Entry<String, String> m : params.entrySet()) {
                builder.add(m.getKey(), m.getValue());
            }
            if(url.equals("fail")){
                url=URL;
            }

            Request request = new Request.Builder()
                    .url(url)
                    .method("GET", null)
                    .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
                    .addHeader("Accept-Encoding", "gzip, deflate, br")
                    .addHeader("Cache-Control", "max-age=0")
                    .addHeader("Connection", "keep-alive")
                    .addHeader("Cookie", "fikker-QZAb-CLqp=K8eRIT3dU8YPkvwKeM7b3tUTKDwpiHgd; fikker-QZAb-CLqp=K8eRIT3dU8YPkvwKeM7b3tUTKDwpiHgd; Hm_lvt_12a875c5d4dbaf89e1c32e4748faf764=1630717474; bgcolor=; font=; size=; fontcolor=; width=; bookid=35478%2C35478; fikker-JfYX-Q0Q8=SnCTQLURylQNETsJmr9OAMOJSBuOejit; fikker-JfYX-Q0Q8=SnCTQLURylQNETsJmr9OAMOJSBuOejit; chapterid=13369516%2C13369545; chaptername=%u7B2C%201%20%u7AE0%20%u91CD%u751F%u7A7F%u8D8A%2C%u7B2C%2030%20%u7AE0%20%u65B0%u7684%u4EA4%u6613%u65B9%u5F0F; Hm_lpvt_12a875c5d4dbaf89e1c32e4748faf764=1630721987")
                    .addHeader("Host", "www.vipkanshu.com")
                    .addHeader("Referer", url)
                    .addHeader("sec-ch-ua", "Chromium;v=92,  Not A;Brand;v=99, Google Chrome;v=92")
                    .addHeader("sec-ch-ua-mobile", "?0")
                    .addHeader("Sec-Fetch-Dest", "document")
                    .addHeader("Sec-Fetch-Mode", "navigate")
                    .addHeader("Sec-Fetch-Site", "same-origin")
                    .addHeader("Sec-Fetch-User", "?1")
                    .addHeader("Upgrade-Insecure-Requests", "1")
                    .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36")
                    .build();
            Response response = OkHttpUtil.getInstance().newCall(request).execute();
            if (response.isSuccessful()) {
                System.out.println(System.currentTimeMillis()-star);
                String content = response.body().string();
                Document doc = Jsoup.parse(content);
                Elements bookname = doc.getElementsByClass("content");
                Element parent= bookname.get(0);
                List<Node> nodes = parent.childNodes();
                Node node = nodes.get(1);
                Element title=(Element)node;
                // Element child = (Element) i;
                String text1 = title.text();
                Element text = doc.getElementById("content");
                star=System.currentTimeMillis();
                String wenben = fiter(text.getAllElements().text());
                System.out.println(System.currentTimeMillis()-star);
                star=System.currentTimeMillis();
                try {
                    fos.write(" \r\n".getBytes());
                    fos.write(" \r\n".getBytes());
                    fos.write(" \r\n".getBytes());
                    fos.write(text1.getBytes(StandardCharsets.UTF_8));
                    fos.write(" \r\n".getBytes());
                    fos.write(" \r\n".getBytes());
                    fos.write(" \r\n".getBytes());
                    fos.write(wenben.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println(System.currentTimeMillis()-star);
                Elements div = doc.getElementsByClass("page_chapter");
                Element element = div.get(0);
              List<Node>  nodes1 = element.childNodes();
                Node   nodes2 = nodes1.get(1);
                Element elementA=(Element )nodes2;
                List<Node> nodes3 = elementA.childNodes();
                Node node1 = nodes3.get(5);
                Element elementAB=(Element )node1;
                String oA = elementAB.select("a").attr("href");
                if(oA.indexOf("index.html")!=-1){
                    return null;
                }
                URL="https://www.vipkanshu.com/" + oA;
                return "https://www.vipkanshu.com/" + oA;
            }else {
                return "fail";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 写入网页文字1
     */
    public static String get2(String url, Map<String, String> params,FileOutputStream fos,int j) {
        long star=System.currentTimeMillis();
        try {
            FormBody.Builder builder = new FormBody.Builder();
            for (Map.Entry<String, String> m : params.entrySet()) {
                builder.add(m.getKey(), m.getValue());
            }
            if(url.equals("fail")){
                url=URL;
            }

            Request request = new Request.Builder()
                    .url(url)
                    .method("GET", null)
                    .build();
            OkHttpClient.Builder builder1 = new OkHttpClient.Builder();
            Response response = builder1.build().newCall(request).execute();
            if (response.isSuccessful()) {
                System.out.println(System.currentTimeMillis()-star);
                String content = new String(response.body().bytes(), "utf-8");
                Document doc = Jsoup.parse(content);
                Elements bookname = doc.getElementsByClass("panel-body content-body content-ext");
                Element parent= bookname.get(0);
                String text2 = parent.text();
                star=System.currentTimeMillis();
                String wenben = fiter(text2);
                System.out.println(System.currentTimeMillis()-star);
                star=System.currentTimeMillis();
                try {
                    fos.write(" \r\n".getBytes());
                    fos.write(" \r\n".getBytes());
                    fos.write(" \r\n".getBytes());

                    fos.write(" \r\n".getBytes());
                    fos.write(" \r\n".getBytes());
                    fos.write(" \r\n".getBytes());
                    fos.write(wenben.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println(System.currentTimeMillis()-star);
                Elements div = doc.getElementsByClass("page_chapter");
                Element element = div.get(0);
                List<Node>  nodes1 = element.childNodes();
                Node   nodes2 = nodes1.get(1);
                Element elementA=(Element )nodes2;
                List<Node> nodes3 = elementA.childNodes();
                Node node1 = nodes3.get(5);
                Element elementAB=(Element )node1;
                String oA = elementAB.select("a").attr("href");
                if(oA.indexOf("index.html")!=-1){
                    return null;
                }
                URL="https://www.51kanshu.org/" + oA;
                return "https://www.51kanshu.org/" + oA;
            }else {
                return "fail";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 去广告语
     * @param text
     * @return
     */
    public static String fiter(String text) {
        for (Iterator<String> iterator = string.iterator(); iterator.hasNext(); ) {
            String next =  iterator.next();
            text = text.replace(next, "");
        }
        return text;
    }

    /**
     * token置换手机号后台接口
     */
    public static JSONObject postRequest(String url, Map<String, String> params) {
        try {
            FormBody.Builder builder = new FormBody.Builder();
            for (Map.Entry<String, String> m : params.entrySet()) {
                builder.add(m.getKey(), m.getValue());
            }
            RequestBody body = builder.build();
            Request request = new Request.Builder().post(body).url(url).build();
            Response response = OkHttpUtil.getInstance().newCall(request).execute();
            if (response.isSuccessful()) {
                String content = response.body().string();
                //System.out.println("response:"+content);
                if (StringUtils.isNotBlank(content)) {
                    JSONObject jsonObject = JSONObject.parseObject(content);
                    return jsonObject;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static final List<String> string = new ArrayList<>();

    static {
        string.add("推荐阅读笔趣阁TVhttps://m.biqugetv.com/https://www.biqugetv.com/");
        string.add("手机端 一秒記住『笔\\趣\\阁→m.\\B\\iq\\u\\g\\eTv.C\\o\\m』為您提供精彩\\小說閱讀。");
        string.add("笔趣阁TV手机端https://m.biqugetv.com/");
        string.add("笔趣阁TV更新最快https://www.biqugetv.com/ https://m.biqugetv.com/");
        string.add("笔趣阁TV首发www.biqugetv.com m.biqugetv.com");
        string.add("”笔趣阁TV手机端https://m.biqugetv.com/");
        string.add("一秒記住『笔♂趣÷阁→WWw.BiqugeTv.Com』為您提供精彩小說閱讀。");
        string.add("一秒記住『笔♂趣÷阁→www.BiqugeTv.Com』為您提供精彩小說閱讀。");
        string.add("老铁!还在找\"大神网文\"免费更新?");
        string.add("百度直接搜索:\"笔趣阁tv\"看免费小说,没毛病!");
        string.add("(www.biqugetv.com=笔趣阁tv)");
        string.add("笔趣阁TV首发www.biqugetv.com m.biqugetv.com");

    }

}
